package lock;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: leetcode-study xunhuanprintnum
 * @Description: lock
 * @Author: 逸伦
 * @Date: 2025/4/8 16:50
 * @Version: 1.0
 */
public class xunhuanprintnum {

	private static int count = 0;
	private static int countMax = 1000;
	private static boolean flag = false;
	private static ReentrantLock lock = new ReentrantLock(false);
	public static void main(String[] args) {

		ExecutorService pool = Executors.newCachedThreadPool();
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			while (count < countMax) {
				try {
					lock.lock();
					if (flag) {
						count++;
						flag = !flag;
						System.out.println("current count is " + count);
					}
				} finally {
					lock.unlock();
				}
			}
			return count;
		},pool);
		CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
			while (count < countMax) {
				try {
					lock.lock();
					if (!flag) {
						count++;
						flag = !flag;
						System.out.println("current count is " + count);
					}
				} finally {
					lock.unlock();
				}
			}
			return count;
		},pool);

		CompletableFuture<Void> all = CompletableFuture.allOf(future, future2);
		all.join();
		System.out.println("done");
	}
}
